#region DocumentHeader
// =============================================    
// Author       : Sai Kumar.M  
// Create date  : 02.11.2013
// Purpose      : Controller for Execute actions for photo gallery view
// ============================================= 
#endregion

#region Name Spaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LenseAPIService.DataAccessLayer;
using CropLense.Models;
using System.Data;
using log4net;
using System.Configuration;
using PagedList;
using Lens.com.Models;
using iConcept.Framework;
#endregion

namespace PhotoGallery.Controllers
{
    public class PhotoGalleryController : Controller
    {

        #region Private Member Varibles
        string FileUploadpath = ConfigurationManager.AppSettings["FileUpload"].ToString();
        private IConceptResourceSet iconceptResourceSet;
        private ResourceSetManager resourceSetManager;
        private static readonly ILog Log = LogManager.GetLogger(typeof(PhotoGalleryController));
        PhotosGallery objPhotoGallery = new PhotosGallery();
        List<PhotosGallery> objListGallery;
        DataAccess objDataAccess = new DataAccess();

        private readonly string partialViewName = "_PagedPictureGallery";
        private readonly int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]);
        #endregion

        #region Public Action Methods
        /// </summary>
        ///  author          :       Sai Kumar.M
        ///  Created         :       02.11.2013
        ///  Purpose         :       This Action method Will render the photo galler view initially
        /// </summary>
        /// <returns>
        /// it will returns the empty view
        /// <returns>
        public ActionResult Index()
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info("Start" + methodBase.Name);
            try
            {
                TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;             
                TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;//Replace atcual
                ViewBag.LensCount = null;

                TempData["ThisDay"] = null;
                TempData["Thisweek"] = null;
                TempData["ThisMonth"] = null;

                Session["ThisDay"] = null;
                Session["Thisweek"] = null;
                Session["ThisMonth"] = null;

                TempData["SearchCrop"] = null;
                Session["SearchCrop"] = null;
                string UserId = DBNull.Value.ToString();
                string cropName = DBNull.Value.ToString();
                string ThisDay = "0";
                string ThisMonth = "0";
                string Thisweek = "0";
                string PublicLense = "1";

                TempData["Lense"] = GlobalConstants.PublicLense;

                DataTable dtReportImages = objDataAccess.GetTopImagepathForReportid(UserId, cropName, ThisDay, Thisweek, ThisMonth, PublicLense);
                if (dtReportImages.Rows.Count > 0)
                {
                    List<ReportImages> liReportImages = dtReportImages.AsEnumerable().Select(row => new ReportImages
                    {
                        ReportId = row.Field<int>("ReportId"),
                        ReportImagePath = FileUploadpath + row.Field<string>("ReportImagePath"),
                        ReportTitle = row.Field<string>("ReportImagePath").ToString(),
                        ReportComments = row.Field<string>("ReportComments"),
                        PostedDate = row.Field<string>("PostedDate")
                    }).ToList();
                    objPhotoGallery.lstImages = liReportImages;
                    objPhotoGallery.PagedListofImages = liReportImages.OrderByDescending(x => x.ReportId).ToPagedList(1, pageSize);
                }
                
            }
            catch (Exception ex)
            {
                Log.Error("Error" + ex);
            }
            finally
            {
                Log.Info("End" + methodBase.Name);
            }
            return View(objPhotoGallery);
        }

        /// <summary>
        /// Created By:  prudhvi
        /// Created Date : 01-11-2013
        /// Purpose : get ImageGallery pictures based on search
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="coll"></param>
        /// <returns></returns>
        /// 
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult GetLenseDetails(string Command, FormCollection coll)
        {
            //string soilname = DBNull.Value.ToString();
            //string irrigationname = DBNull.Value.ToString();

            if (coll["value"] != null)
            {
               
                    try
                    {

                        resourceSetManager = new ResourceSetManager(Convert.ToInt32(coll["value"]), Convert.ToInt32(Session["ProjectId"]), Convert.ToInt32(Session["CountryId"]), Convert.ToInt32(Session["ModuleId"]), HttpRuntime.AppDomainAppPath);
                        //SetUIText();
                        objPhotoGallery.LanguagesList = (SelectList)Session["objLanguagesist"];
                        objPhotoGallery.LanguagesList.Where(a => a.Value == coll["value"]).Select(a => a.Selected = true);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message, ex);
                        // ScriptManager.RegisterStartupScript(this, typeof(Page), "script", "alert(\" " + ex.Message + "\");", true);
                    }
             
            }

            //  Session["UserID"] = 39;
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info("Start" + methodBase.Name);
            try
            {

                if (Command == GlobalConstants.Login)
                {
                    string username = coll[GlobalConstants.master_txtUserName];
                    string password = coll[GlobalConstants.master_txtPassword];
                    int isValiduser = objDataAccess.ValidateUser(username, password);
                    if (isValiduser > 0)
                    {
                        Session["UserID"] = isValiduser;                       
                        string MobileNo = objDataAccess.GetUserInfo(Convert.ToString(Session["UserID"]));
                        if (!string.IsNullOrEmpty(MobileNo))
                        {
                            Session["MobileNo"] = MobileNo;
                        }
                        else
                        {
                            Session["MobileNo"] = GlobalConstants.Unavailable;
                        }
                    }
                    else
                    {
                        ViewBag.Success = GlobalConstants.InvalidUser;
                        TempData["Lense"] = GlobalConstants.PublicLense;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.PubliclenseImageUrl;
                        DataTable dtReportImagestemp = objDataAccess.GetTopImagepathForReportid(null, null, GlobalConstants.zero, GlobalConstants.zero, GlobalConstants.zero, GlobalConstants.one);
                        if (dtReportImagestemp.Rows.Count > 0)
                        {
                            List<ReportImages> liReportImages = dtReportImagestemp.AsEnumerable().Select(row => new ReportImages
                            {
                                ReportId = row.Field<int>(GlobalConstants.ReportId),
                                ReportImagePath = FileUploadpath + row.Field<string>(GlobalConstants.ReportImagePath),
                                ReportTitle = !string.IsNullOrEmpty(row.Field<string>(GlobalConstants.ReportImagePath).ToString()) ? row.Field<string>(GlobalConstants.ReportImagePath).ToString() : "Unavailable",
                                ReportComments = row.Field<string>(GlobalConstants.ReportComments),
                                PostedDate = row.Field<string>(GlobalConstants.PostedDate)
                            }).ToList();
                            objPhotoGallery.lstImages = liReportImages;
                            objPhotoGallery.PagedListofImages = liReportImages.OrderByDescending(x => x.ReportId).ToPagedList(1, pageSize);
                        }
                        return View("Index", objPhotoGallery);
                    }
                }

                ViewBag.hidelogin = GlobalConstants.Hide;

                string Cropname = string.Empty;
                string UserId = string.Empty;
                if (Session["UserID"] != null)
                    UserId = Session["UserID"].ToString();
                string ThisDay, ThisMonth, Thisweek;
                string PublicLense = string.Empty;


                //  Thisweek = coll["Command"];
                ThisDay = coll[GlobalConstants.Todayhidden];
                Thisweek = coll[GlobalConstants.Thisweekhidden];
                ThisMonth = coll[GlobalConstants.Thismonthhidden];
                Cropname = coll[GlobalConstants.Crophidden];

                if (Cropname != "")
                {
                    TempData["Crop"] = "on " + coll[GlobalConstants.Crophidden];
                    TempData["SearchCrop"] = coll[GlobalConstants.Crophidden];
                    Session["SearchCrop"] = coll[GlobalConstants.Crophidden];
                }
                TempData["ThisMonth"] = null;
                TempData["Thisweek"] = null;
                TempData["ThisDay"] = null;

                Session["ThisDay"] = null;
                Session["Thisweek"] = null;
                Session["ThisMonth"] = null;

                if (ThisDay == GlobalConstants.checkeds)
                {
                    ThisDay = GlobalConstants.one;
                    TempData["ThisDay"] = 1;
                    Session["ThisDay"] = 1;
                }
                else
                    ThisDay = GlobalConstants.zero;
                if (Thisweek == GlobalConstants.checkeds)
                {
                    Thisweek = GlobalConstants.one;
                    TempData["Thisweek"] = 1;
                    Session["Thisweek"] = 1;
                }
                else
                    Thisweek = GlobalConstants.zero;
                if (ThisMonth == GlobalConstants.checkeds)
                {
                    ThisMonth = GlobalConstants.one;
                    TempData["ThisMonth"] = 1;
                    Session["ThisMonth"] = 1;
                }
                else
                    ThisMonth = GlobalConstants.zero;
                ViewBag.Lense = GlobalConstants.PublicLense;
                TempData["Lense"] = GlobalConstants.PublicLense;
                TempData["PublicLenseImageUrl"] = GlobalConstants.PubliclenseImageUrl;                
                if (!string.IsNullOrEmpty(coll[GlobalConstants.Command]))
                {
                    if (coll[GlobalConstants.Command].Contains(GlobalConstants.MyLense))
                    {
                        TempData["Lense"] = GlobalConstants.MyLense;                       
                        TempData["MyLenseImageUrl"] = GlobalConstants.SelectMylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.PubliclenseImageUrl;
                        if (Session["UserID"] == null)
                        {
                            ViewBag.InvalidUser = GlobalConstants.InvalidUser;
                            //return new JavaScriptResult{ Script = "alert('Enter the proper value for zipcode');" };
                            return RedirectToAction("Index", "PhotoGallery");
                        }
                        Session["CurrentLense"] = GlobalConstants.MyLense;
                        PublicLense = GlobalConstants.zero;
                    }
                    else if (coll["Command"].Contains(GlobalConstants.PublicLense))
                    {
                        ViewBag.Lense = GlobalConstants.PublicLense;
                        Session["CurrentLense"] = GlobalConstants.PublicLense;

                        TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;
                        if (Session["UserID"] == null)
                        {
                            return RedirectToAction("Index", "PhotoGallery");
                        }
                        PublicLense = GlobalConstants.one;
                        UserId = string.Empty;
                    }

                    else if (Session["CurrentLense"] == GlobalConstants.MyLense)
                    {
                        TempData["Lense"] = GlobalConstants.MyLense;
                        TempData["MyLenseImageUrl"] = GlobalConstants.SelectMylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.PubliclenseImageUrl;
                        if (Session["UserID"] == null)
                        {
                            ViewBag.InvalidUser = GlobalConstants.InvalidUser;
                            //return new JavaScriptResult{ Script = "alert('Enter the proper value for zipcode');" };
                            return RedirectToAction("Index", "PhotoGallery");
                        }
                        Session["CurrentLense"] = GlobalConstants.MyLense;
                        PublicLense = GlobalConstants.zero;
                    }
                    else if (Session["CurrentLense"] == GlobalConstants.PublicLense)
                    {
                        ViewBag.Lense = GlobalConstants.PublicLense;
                        Session["CurrentLense"] = GlobalConstants.PublicLense;

                        TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;
                        if (Session["UserID"] == null)
                        {
                            return RedirectToAction("Index", "PhotoGallery");
                        }
                        PublicLense = GlobalConstants.one;
                        UserId = string.Empty;
                    }
                    else if (coll[GlobalConstants.Command].Contains(GlobalConstants.Login))
                    {
                        TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;
                        PublicLense = GlobalConstants.one;
                        UserId = string.Empty;
                    }

                    else
                    {
                        TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;
                        TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;
                        PublicLense = GlobalConstants.one;
                        UserId = string.Empty;

                    }

                }

                else
                {
                    TempData["MyLenseImageUrl"] = GlobalConstants.MylenseImageUrl;
                    TempData["PublicLenseImageUrl"] = GlobalConstants.SelectPubliclenseImageUrl;
                    PublicLense = GlobalConstants.one;
                    if (Command != GlobalConstants.predictiveLink)
                    {
                        UserId = "";
                    }

                }
                if (Cropname == "Crophidden")
                {
                    TempData["SearchCrop"] =null;
                    Session["SearchCrop"] = null;
                    Cropname = string.Empty;
                }
                if (Cropname == null)
                {
                    if (!string.IsNullOrWhiteSpace(ControllerContext.RouteData.GetRequiredString("id")))
                    {
                        Cropname = ControllerContext.RouteData.GetRequiredString("id").ToString();
                        UserId = "";
                    }
                }

                Session["DynamicLense"] = PublicLense;
                DataTable dtReportImages = objDataAccess.GetTopImagepathForReportid(UserId, Cropname, ThisDay, Thisweek, ThisMonth, PublicLense);
                if (dtReportImages.Rows.Count > 0)
                {
                    var listofImages = GetAllPictures(dtReportImages);
                    objPhotoGallery.PagedListofImages = listofImages.OrderByDescending(x => x.ReportId).ToPagedList(1, pageSize);

                }
                // For Soil lense


                else
                {

                    ViewBag.LensCount = GlobalConstants.NotExist;
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error" + ex);
            }
            finally
            {
                Log.Info("End" + methodBase.Name);
            }

            return View("Index", objPhotoGallery);
        }

        private List<ReportImages> GetAllPictures(DataTable dtReportImages)
        {

            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info("Start" + methodBase.Name);
            try
            {
                ViewBag.LensCount = dtReportImages.Rows.Count.ToString();
                List<ReportImages> liReportImages = dtReportImages.AsEnumerable().Select(row => new ReportImages
                {
                    ReportId = row.Field<int>("ReportId"),
                    ReportImagePath = FileUploadpath + row.Field<string>("ReportImagePath"),
                    ReportTitle = Convert.ToString(row.Field<string>("ReportTitle")),
                    ReportComments = row.Field<string>("ReportComments"),
                    PostedDate = row.Field<string>("PostedDate")
                }).ToList();
                objPhotoGallery.lstImages = liReportImages;


                return liReportImages;
            }
            catch (Exception ex)
            {
                Log.Error("Error" + ex);
                return null;
            }
            finally
            {
                Log.Info("End" + methodBase.Name);
            }
        }


        [HttpGet]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult Filter(int page)
        {
            // Adds Try Catch Block along with Log file.
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info("Start" + methodBase.Name);
            try
            {
                string userId = Convert.ToString(Session["UserID"]);
                string currentlenseName = Convert.ToString(Session["CurrentLense"]);
                string Cropname = string.Empty;

                string ThisDay = string.Empty;
                string ThisMonth = string.Empty;
                string Thisweek = string.Empty;

                
                
                
                string PublicLense = "1";

                string UserId = DBNull.Value.ToString();
                string cropName = DBNull.Value.ToString();
                if (Session["ThisDay"]!=null)
                {
                    ThisDay = Session["ThisDay"].ToString();
                }
                else
                {
                     ThisDay = "0";
                }
                if (Session["ThisMonth"] != null)
                {
                    ThisMonth = Session["ThisMonth"].ToString();
                }
                else
                {
                     ThisMonth = "0";
                }
                if (Session["Thisweek"] != null)
                {
                    Thisweek = Session["Thisweek"].ToString();
                }
                else
                {
                     Thisweek = "0";
                }

               

                if (Session["DynamicLense"]!=null)
                {
                    if (Session["DynamicLense"].ToString() == GlobalConstants.one)
                    {
                        
                        UserId = "";
                    }
                    else
                    {
                        UserId = Session["UserID"].ToString();
                    }
                    PublicLense = Session["DynamicLense"].ToString();
                    
                }


                cropName = "Crophidden";

                List<ReportImages> allPictiresList = new List<ReportImages>();
                if (cropName == "Crophidden")
                {
                    Session["SearchCrop"] = null;
                    cropName = string.Empty;
                }
                if (Cropname == null)
                {
                    if (!string.IsNullOrWhiteSpace(ControllerContext.RouteData.GetRequiredString("id")))
                    {
                        Cropname = ControllerContext.RouteData.GetRequiredString("id").ToString();
                        UserId = "";
                    }
                }

                if (Request.IsAjaxRequest())
                {
                    DataTable dtReportImages = objDataAccess.GetTopImagepathForReportid(UserId, cropName, ThisDay, Thisweek, ThisMonth, PublicLense);
                    if (dtReportImages.Rows.Count > 0)
                    {
                        allPictiresList = GetAllPictures(dtReportImages);

                    }
                    else
                    {

                        ViewBag.LensCount = GlobalConstants.NotExist;
                    }



                    return PartialView(partialViewName, allPictiresList.ToPagedList(page, pageSize));
                }
                return View("Index", allPictiresList.ToPagedList(page, pageSize));

            }
            catch (Exception ex)
            {
                Log.Error("Error" + ex);
                return null;
            }
            finally
            {
                Log.Info("End" + methodBase.Name);
            }
        }

        /// <summary>
        /// Method used to set the default values
        /// </summary>
        private List<Languages> SetDefaultLanguage()
        {
            var currentMethod = (new System.Diagnostics.StackFrame()).GetMethod().Name;
            //Log.Info(GlobalConstants.StrStart + currentMethod);
            try
            {
                #region Language binding
                DataSet objDataSet = new DataSet();
                objDataSet = Generic.GetDefaultLanguageSettings();
                if (objDataSet != null && objDataSet.Tables.Count > 0)
                {
                    if (objDataSet.Tables[0].Rows.Count > 0)
                    {
                        Session["CountryId"] = Convert.ToString(objDataSet.Tables[0].Rows[0]["CountryId"]);
                        Session["ProjectId"] = Convert.ToString(objDataSet.Tables[0].Rows[0]["ProjectId"]);
                        Session["ModuleId"] = ConfigurationManager.AppSettings["ModuleId"];
                    }
                }
                if (objDataSet != null && objDataSet.Tables[1].Rows.Count > 0)
                {
                    Session[GlobalConstants.SessionLanguageId] = objDataSet.Tables[0].Rows[0]["DefaultLanguageId"];

                    List<Languages> objListLanguages = bindDropDown(objDataSet.Tables[1]);
                    Session["defaultlanguageId"] = objDataSet.Tables[0].Rows[0]["DefaultLanguageId"];
                    Session["ProjectId"] = objDataSet.Tables[0].Rows[0]["ProjectId"];
                    Session["CountryId"] = objDataSet.Tables[0].Rows[0]["CountryId"];
                    resourceSetManager = new ResourceSetManager(Convert.ToInt32(objDataSet.Tables[0].Rows[0]["DefaultLanguageId"]), Convert.ToInt32(objDataSet.Tables[0].Rows[0]["ProjectId"]), Convert.ToInt32(objDataSet.Tables[0].Rows[0]["CountryId"]), Convert.ToInt32(Session["ModuleId"]), HttpRuntime.AppDomainAppPath);
                    SetUIText();
                    return objListLanguages;
                }
                return null;
                #endregion
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                return null;
            }
        }

        private void SetUIText()
        {
            var currentMethod = (new System.Diagnostics.StackFrame()).GetMethod().Name;
            Log.Info(GlobalConstants.StrStart + currentMethod);
            try
            {
                iconceptResourceSet = resourceSetManager.GetResourceSetObject();
                objPhotoGallery.MobileNo = iconceptResourceSet.GetString("Login");
                objPhotoGallery.PlesaelogintoCropLense = iconceptResourceSet.GetString("");
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
            }
        }

        private List<Languages> bindDropDown(DataTable dataTable)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info("Start" + methodBase.Name);
            try
            {
                List<Languages> objListLanguages = new List<Languages>();
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    string langID = dataTable.Rows[i][0].ToString();
                    string lang = dataTable.Rows[i][1].ToString();
                    objListLanguages.Add(new Languages { LanguageID = langID, LanguageName = lang });
                }
                return objListLanguages;
            }
            catch (Exception ex)
            {
                Log.Error("Error" + ex);
                return null;
            }
            finally
            {
                Log.Info("End" + methodBase.Name);
            }
        }


        #endregion
    }
}
